package org.jeecg.modules.solitaire_app.yuyin.utils;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import okhttp3.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MediaUrlUtil {

    public static final String API_KEY = "h1F1ioravUzz2KcdscI5DMIE";
    public static final String SECRET_KEY = "b4Fp2lbjHyW2VZaDr899poCtpIH4CbWA";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();


    public static String getMediaUrl(String text, int voice) throws IOException {
        MediaType mediaType = MediaType.parse("application/json");

        List<String> taskIds = new ArrayList<>();
        taskIds.add(getTaskId(text, voice));
        JSONObject jsonPara = new JSONObject();
        jsonPara.putOpt("task_ids", taskIds);

        System.out.println(jsonPara.toString());

        RequestBody body = RequestBody.create(mediaType, "{\"task_ids\":[\"66121a70679f6f000100b63e\"]}");
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rpc/2.0/tts/v1/query?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();

        Response response = HTTP_CLIENT.newCall(request).execute();
        JSONObject jsonObject = new JSONObject(response.body().string());
        if (!jsonObject.containsKey("tasks_info")) {
            return null;
        }
        JSONObject taskInfoObj = jsonObject.getJSONArray("tasks_info").getJSONObject(0);
        String mediaUrl = taskInfoObj.getJSONObject("task_result").getStr("speech_url");
        return mediaUrl;
    }


    static String getTaskId(String text, int voice) throws IOException {
        MediaType mediaType = MediaType.parse("application/json");

        JSONObject jsonPara = new JSONObject();
        jsonPara.putOpt("text", text);
        jsonPara.putOpt("voice", voice);
        jsonPara.putOpt("format", "mp3-16k");
        jsonPara.putOpt("lang", "zh");
        jsonPara.putOpt("speed", 5);
        jsonPara.putOpt("pitch", 5);
        jsonPara.putOpt("volume", 5);
        jsonPara.putOpt("enable_subtitle", 0);

        RequestBody body = RequestBody.create(mediaType, jsonPara.toString());
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rpc/2.0/tts/v1/create?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        JSONObject jsonObject = new JSONObject(response.body().string());
        String taskId = jsonObject.getStr("task_id");
        return taskId;
    }


    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getStr("access_token");
    }
}
